package day1;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class SocketServer {

    private static final Logger log = LoggerFactory.getLogger(SocketServer.class);

    public static void main(String[] args) throws IOException {

        //创建selector
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(6666));
        ssc.configureBlocking(false);

        /**
         * 通道发生的四种事件：
         *  服务端获取到连接请求  accept
         *  客户端连接到服务端   connet
         *  可读事件  read
         *  可写事件  write
         */
        //注册到selector中返回通道key  (selector,关注事件,)
        SelectionKey selectionKey = ssc.register(selector, SelectionKey.OP_ACCEPT, null);

//        List<SocketChannel> list = new ArrayList<>();
        while (true) {
            //select方法，没有事件发生，线程阻塞，有事件，线程才会回复运行
            //select方法，有事件发生，不阻塞，要么处理要么取消
            selector.select();
            //处理事件，selectedkeys 内部包含了所有发生的事件
            //selector有未处理事件时不会阻塞
            //事件发生时通道的hash值会记录在SelectionKey中
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                //处理key时要从selectkey集合中删除，否则下次处理会有问题
                iter.remove();

                //区分事件类型：   连接   接收    写    读    有效
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}", sc);
                    log.debug("scKey:{}", scKey);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        //获取selectedKey上关联的附件
                        ByteBuffer buffer = (ByteBuffer)key.attachment();
                        int read = channel.read(buffer);
                        //-1表示客户端断开连接
                        if (read==-1){
                            //清除通道
                            key.channel();
                        }else {
//                            buffer.flip();
                            split(buffer);
                            //如果buffer容量满了,则再创建一个byteBuffer，容量是原bytebuffer的二倍
                            if (buffer.position() == buffer.limit()){
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }
                    }catch (IOException e){
                        e.printStackTrace();;
                        key.channel();
                    }
                }
            }
        }
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                ByteBufferUtil.debugAll(target);
            }
        }
        source.compact();
    }
}
